import React, { useRef , useState, useEffect  }from 'react'
import { Space ,SearchBar,Toast, SearchBarRef,Button} from 'antd-mobile'
import { fetchItems} from '@/api'
import { useNavigate, useDispatch } from 'umi'
import './style.scss'
import Items from './components/Items'

function Search() {
  let [name, setName] = useState('');
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const searchRef = useRef<SearchBarRef>(null)
  const [items, setItems] = useState<any[]>([]);
  // 商品获取
  useEffect(() => {
    getItems() 
  }, [name])
  // 搜索方法
  const getItems = () => {
    setItems([])
   fetchItems({
    nameLike : name
    }).then((res: { data: { code: number; data: { result: React.SetStateAction<any[]> } } }) => {
      if (res.data.code === 0) {
        setItems([
          ...items,
          ...res.data.data.result
        ])
      }
      if(res.data.code === 700) {
        // 没有数据
        Toast.show('暂无数据')
      }
    })
  }
  //点击图片添加商品数据
  const addCartItem = (id: number) => {
    dispatch({
      type: 'cart/addItem',
      data: {
        goodsId: id,
        number: 1
      }
    })
  }
  return (
    <div>
      <Space block direction='vertical'>
          <SearchBar
            ref={searchRef}
            placeholder='请输入内容'
            showCancelButton
            onSearch={val => {
              setName(name=val ) 
            }}
            onCancel={() => {
              Toast.show('取消搜索')
            }}
          />
          <Space>
            <Button
              onClick={() => {
                searchRef.current?.clear()
              }}
            >
              清空内容
            </Button>
            <Button
              onClick={() => {
                searchRef.current?.focus()
              }}
            >
              激活
            </Button>
            <Button
              onClick={()=>{
                navigate(-1)
              }}
            >
              取消返回
            </Button>
          </Space>
        </Space>
        {
          name ?
          <Items items={items} clickItems={
            (id: number) => {
              navigate(`/detail/${id}`)
            }
          } clickCartIcon={ 
            (id: number) => {
              addCartItem(id)
            }
           }/>
           :
           <></>
        }
    </div>
  )
}
export default Search
